package com.wedo.upload.service;

import com.obs.services.ObsClient;
import com.wedo.common.utils.IdWorker;
import com.wedo.upload.config.OBSProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {

    private static final List<String> CONTEXT_TYPE = Arrays.asList("image/png","image/jpeg");

    @Autowired
    private OBSProperties obsProperties;

    @Autowired
    private IdWorker idWorker;

    public String uploadImage(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        // 校验文件类型
        String contentType = file.getContentType();
        if (!CONTEXT_TYPE.contains(contentType)) {
            return null;
        }

        try {
            // 校验文件内容
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                return null;
            }

            // 保存到服务器
            String ext = StringUtils.substringAfterLast(originalFilename, ".");

            // 返回url,进行回显
            // return "http://image.leyou.com/" + originalFilename;
            String endPoint = this.obsProperties.getEndPoint();
            String ak = this.obsProperties.getAk();
            String sk = this.obsProperties.getSk();

            String randomFileName = idWorker.nextId() + "." + ext;

            // 创建ObsClient实例
            ObsClient obsClient = new ObsClient(ak, sk, endPoint);
            return obsClient.putObject("wedo.image", randomFileName,file.getInputStream()).getObjectUrl();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;


    }
}
